import { Service } from 'egg';
import { Admin } from '../model/Admin';
import * as md5 from 'blueimp-md5';
import { IdentifyingCode } from '../model/Identifying_code';

export default class AdminService extends Service {
    /**
     * 处理后台登录事件
     * @param {string} admin_username
     * @param {string} admin_password
     * @returns {Promise<any>}
     */
    public async login(admin_username: string, admin_password: string) {
        try {
            admin_password = md5(admin_password + 'linglan');
            const admin: any = await this.ctx.model.Admin.findOne<Admin>({
                attributes: ['admin_id', 'admin_username', 'admin_password', 'admin_status'],
                where: {
                    admin_username,
                    admin_password
                },
            });
            if (!admin) {
                throw new Error(JSON.stringify({ code: 2, msg: '登录失败（用户名或密码错误）' }));
            }
            const admin_status = admin.admin_status;
            if (admin_status == '2') {
                throw new Error(JSON.stringify({ code: 2, msg: '登录失败（您已被停用）' }));
            }
            return admin;
        } catch (e) {
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 更新token
     * @param {string} admin_username
     * @param {string} admin_token
     * @param {string} updated_time
     * @returns {Promise<any>}
     */
    public async updateToken(admin_id: string, admin_token: string) {
        const result = await this.ctx.model.Admin.update({ admin_token }, {
            where:
            {
                admin_id,
            },
        },
        );
        if (!result) {
            throw new Error(JSON.stringify({ code: 2, msg: '更新token失败' }));
        }
        return result;
    }

    /**
     *
     * @param token 根据token查找用户
     */
    public async searchAdminByToken(token: string) {
        try{
            const admin = await this.ctx.model.Admin.findOne<Admin>({
                attributes: ['admin_id', 'admin_username', 'admin_password'],
                where: {
                    admin_token: token,
                },
            });
            if (!admin) {
                throw new Error(JSON.stringify({ code: -1, msg: '您还未登录，请登录' }));
            }
            return admin;
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     *
     * @param token 根据token查找用户
     */
    public async searchAdminIdByToken(token: string) {
        try{
            const admin = await this.ctx.model.Admin.findOne<Admin>({
                attributes: ['admin_id', 'admin_username', 'admin_password'],
                where: {
                    admin_token: token,
                },
            });
            if (!admin) {
                return { admin_id: '' };
            }
            return admin;
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 创建管理员
     * @param param 
     */
    public async createAdmin(param: any) {
        try{
            param.admin_username = this.ctx.helper.trim(param.admin_username);
            const checkResult: any = await this.ctx.model.Admin.findOne<Admin>({ attributes: ['admin_id'], where: { admin_username: param.admin_username, is_delete: '0' } });
            if (checkResult) {
                throw new Error(JSON.stringify({ code: 2, msg: '该账号已存在，创建失败' }));
            }
            const resultSMS: any = await this.ctx.model.IdentifyingCode.findOne<IdentifyingCode>({
                attributes: ['identifying_code_id', 'created_at'],
                where: { identifying_code: param.admin_code, phone: param.admin_phone }
            });
            if (!resultSMS) {
                throw new Error(JSON.stringify({ code: 2, msg: '验证码不正确' }));
            }
            const { created_at } = resultSMS;
            const date = new Date();
            const currentDate = date.toLocaleString();
            const minutes = this.ctx.helper.getMinutes(created_at, currentDate);
            if (minutes > 5) {
                throw new Error(JSON.stringify({ code: 2, msg: '验证码已过期' }));
            }
            const submitData: any = {};
            submitData.admin_id = this.ctx.helper.genUUID();
            submitData.admin_username = param.admin_username;
            submitData.admin_password = md5(param.admin_password + 'linglan');
            submitData.admin_token = '';
            submitData.admin_phone = param.admin_phone;
            submitData.admin_remark = param.admin_remark;
            submitData.created_by = param.admin_id;
            submitData.admin_status = '1';
            submitData.is_delete = '0';
            const result = await this.ctx.model.Admin.create(submitData);
            if (!result) {
                throw new Error(JSON.stringify({ code: 2, msg: '创建失败' }));
            }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 查找管理员
     * @param param
     */
    public async searchAdmin() {
        try{
            const admin: any = await this.ctx.model.Admin.findAll<Admin>({
                attributes: ['admin_id', 'admin_username', 'admin_phone', 'admin_remark', 'admin_status'],
                order: [['created_at', 'DESC']]
            });
            if (admin.length <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
            }
            return admin;
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 修改管理员
     */
    public async udpateAdmin(param: any) {
        try{
            const admin_id = param.target_admin_id;
            const admin_password = md5(param.target_admin_password + 'linglan');
            const result = await this.ctx.model.Admin.update({ admin_password, updated_by: param.admin_id },
                {
                    where: { admin_id }
                });
            if (result[0] <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
            }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 重绑手机号
     */
    public async udpateAdminPhone(param: any) {
        try{
            const checkResult: any = await this.ctx.model.Admin.findOne<Admin>({ attributes: ['admin_id', 'admin_username'], where: { admin_id: param.admin_id, is_delete: '0' } });
            if (!checkResult) {
                throw new Error(JSON.stringify({ code: 2, msg: '没有找到该用户' }));
            }
            const resultSMS: any = await this.ctx.model.IdentifyingCode.findOne<IdentifyingCode>({
                attributes: ['identifying_code_id', 'created_at'],
                where: { identifying_code: param.admin_code, phone: param.admin_phone }
            });
            if (!resultSMS) {
                throw new Error(JSON.stringify({ code: 2, msg: '验证码不正确' }));
            }
            const { created_at } = resultSMS;
            const date = new Date();
            const currentDate = date.toLocaleString();
            const minutes = this.ctx.helper.getMinutes(created_at, currentDate);
            if (minutes > 5) {
                throw new Error(JSON.stringify({ code: 2, msg: '验证码已过期' }));
            }
            const admin_id = param.target_admin_id;
            const admin_phone = param.admin_phone;
            const result = await this.ctx.model.Admin.update({ admin_phone, updated_by: param.admin_id },
                {
                    where: { admin_id }
                });
            if (result[0] <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
            }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 启用，停用管理员
     */
    public async startAndStopAdmin(param: any) {
        try{
            const result = await this.ctx.model.Admin.update({ admin_status: param.type, updated_by: param.admin_id }, { where: { admin_id: param.target_admin_id } });
            if (result[0] <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
            }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 找回密码
     * @param param 
     */
    public async forgetPassword(param: any) {
        try{
            param.admin_username = this.ctx.helper.trim(param.admin_username);
            const { admin_username, admin_password, code } = param;
            const result: any = await this.ctx.model.Admin.findOne<Admin>({ attributes: ['admin_id', 'admin_phone'], where: { admin_username, is_delete: '0' } });
            if (!result) {
                throw new Error(JSON.stringify({ code: 2, msg: '没有找到该用户，请确认账号是否有误' }));
            }
            const admin_phone = result.admin_phone;
            const resultSMS: any = await this.ctx.model.IdentifyingCode.findOne<IdentifyingCode>({
                attributes: ['identifying_code_id', 'created_at'],
                where: { identifying_code: code, phone: admin_phone }
            });
            if (!resultSMS) {
                throw new Error(JSON.stringify({ code: 2, msg: '验证码不正确' }));
            }
            const { created_at } = resultSMS;
            const date = new Date();
            const currentDate = date.toLocaleString();
            const minutes = this.ctx.helper.getMinutes(created_at, currentDate);
            if (minutes > 5) {
                throw new Error(JSON.stringify({ code: 2, msg: '验证码已过期' }));
            }
            const admin_id = result.admin_id;
            const updateResult: any = await this.ctx.model.Admin.update({ admin_password: md5(admin_password + 'linglan') }, { where: { admin_id } });
            if (updateResult[0] <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
            }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 发送验证码
     * @param param 
     */
    public async sendSMS(param: any) {
        try{
            param.admin_username = this.ctx.helper.trim(param.admin_username);
            const { admin_username } = param;
            const result: any = await this.ctx.model.Admin.findOne<Admin>({ attributes: ['admin_id', 'admin_phone'], where: { admin_username, is_delete: '0' } });
            if (!result) {
                throw new Error(JSON.stringify({ code: 2, msg: '没有找到该用户，请确认账号是否有误' }));
            }
            const admin_phone = result.admin_phone;
            if (!admin_phone) {
                throw new Error(JSON.stringify({ code: 2, msg: '该用户没有绑定手机号' }));
            }
            const sendResult: any = await this.ctx.service.employeeService.sendSMS({ phone: admin_phone });
            if (sendResult.code === 2) {
                throw new Error(JSON.stringify({ code: 2, msg: sendResult.msg }));
            }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

}
